package com.stylefeng.guns.modular.system.task;

import java.net.URI;
import java.net.URL;
import java.util.List;

import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.util.HttpClientUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;
import com.stylefeng.guns.modular.system.model.ControlData;
import com.stylefeng.guns.modular.system.model.Gpdata;
import com.stylefeng.guns.modular.system.service.IGpdataService;

@Service
public class ControlImportTask{

	private Logger log = LoggerFactory.getLogger(ControlImportTask.class);
	
	private static final HttpClientUtil clientUtil = new HttpClientUtil();
	
	@Autowired
	private IGpdataService iGpdataService;

	public void execute(boolean isHoliday) {
		String url = ImportContants.getControlDataPathStr(1);
		HttpGet httpGet = HttpClientUtil.getGetRequest();
		try {
			URL http = new URL(url);
			URI uri = new URI(http.getProtocol(), http.getHost(), http.getPath(), http.getQuery(), null);
			httpGet.setURI(uri);
			String json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
			JSONObject jsonObj = JSON.parseObject(json);
			int pages = jsonObj.getIntValue("pages");
			parseData(jsonObj.getString("data"));
			for(int i= 2; i <=pages ; i++){
				url = ImportContants.getControlDataPathStr(i);
				http = new URL(url);
				uri = new URI(http.getProtocol(), http.getHost(), http.getPath(), http.getQuery(), null);
				httpGet.setURI(uri);
				json = clientUtil.executeAndGetWithFailedRetry(httpGet, 6,10001);
				jsonObj = JSON.parseObject(json);
				parseData(jsonObj.getString("data"));
			}
		} catch (Exception e) {
			log.error("get control data is error!" + e);
		}finally{
			httpGet.abort();
		}
	}

	private void parseData(String json) {
		List<ControlData> channelItemList = JSON.parseArray(json,ControlData.class);
		for (ControlData controlData : channelItemList) {
			Wrapper<Gpdata> gpdataw = new EntityWrapper<>();
			gpdataw.eq("g_dm", controlData.getCode());
			Gpdata gpdata = iGpdataService.selectOne(gpdataw);
			if(gpdata != null){
				gpdata.setgJgcyd(controlData.getJGCYD());
				gpdata.setgJgcydType(controlData.getJGCYDType());
				gpdata.setgPeration(controlData.getPERation());
				gpdata.setgUdate(controlData.getTDate());
				gpdata.setgZlcb(controlData.getZLCB());
				iGpdataService.updateById(gpdata);
			}
		}
	}
}
